package com.da.core.app.impl;

import com.da.core.app.BaseApp;
import com.da.core.context.Context;
import com.da.core.context.Session;
import com.da.core.context.impl.BIOContext;
import com.da.core.middleware.ErrorMiddleware;
import com.da.core.middleware.FlushMiddleware;
import com.da.core.util.Utils;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author da
 * @time 2023/9/16 上午 10:46
 */
public class BIOApp implements BaseApp {
    private Session session;

    public BIOApp() {
//        注册中间件
        middlewares.add(new FlushMiddleware());
        middlewares.add(new ErrorMiddleware());
    }

    @Override
    public Session getSession() {
        return this.session;
    }

    @SuppressWarnings("all")
    @Override
    public void start(int port) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            Utils.printStartInfo("BIO", port);
            while (true) {
//                等待连接
                Socket clientSocket = serverSocket.accept();
//                使用线程池来处理客户端请求
                executorService.execute(() -> handleBioRequest(clientSocket));
            }
        } catch (IOException e) {
            if (e instanceof java.net.BindException) {
                System.err.println("[BIO]错误提示: 端口 " + port + " 已经被占用了");
            }
            throw new RuntimeException(e);
        } finally {
            executorService.shutdown();
        }
    }

    @Override
    public void setSession(Session session) {
        this.session = session;
    }

    private void handleBioRequest(Socket clientSocket) {
        Context ctx = new BIOContext(clientSocket, this);
        if (null != ctx.getMethod() && null != ctx.getUrl()) {
            System.out.println("[BIO] 收到 [" + ctx.getMethod() + " " + ctx.getUrl() + "] 的请求");
        }
        handleRequest(ctx);
    }
}
